package com.sky.controller;

import com.jfinal.core.Controller;

import io.jboot.web.controller.annotation.RequestMapping;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * @author：sky-吴
 * 日期：2020/4/23
 * 提供出来的接口，入参包括用户名，密码，短信内容。需要调用的时候，直接传这些内容就可以发送。
 */
@RequestMapping("/msg2")
public class MessageController2 extends Controller {

	String userCode="STJ_XTY_00001001";
	String userPass="MXHunOsi";

	/**
	 *
	 * userCode string 登录名称
	 * userPass string 登录密码
	 * DesNo string 手机号码(每次只能提
	 * 交 1 个号码)
	 * Msg string 短信内容
	 * autograph string 签名编号，非必填， 留空
	 * customerUuid string 用户标识字段，非必填（最大长度 32 位）
	 * https 服务引用地址为： https://118.178.116.15:8443/winnerrxd/api/trigger/
	 * string 成功：返回本次提交的批次号, 比如2004231745612875963 失败:返回错误码, 比如:-7 , -5
	 * localhost:8080/msg2/sendAMsg
	 */

	public  void sendAMsg(String userCode, String userPass,  String DesNo , String Msg) {
		String url = "https://118.178.116.15:8443/winnerrxd/api/trigger/SendMsg ";
		DesNo="15932072636";
		/*Msg格式 签名必须有, 没有签名就报错, 但是内容随你写, 只不过没有头像, 能写中文 */
		Msg="1234【通联支付】"; //
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("userCode", userCode);
		paramMap.put("userPass", userPass);
		paramMap.put("DesNo", DesNo);
		paramMap.put("autograph", "");

		paramMap.put("Msg", Msg);
		paramMap.put("customerUuid", "");
		//paramMap.put("smsType",smsType.toString());
		try {
			//GET请求
			final String getResult = ""; //httpsGet(url, paramMap);
			System.out.println(getResult);
			//POST请求
			String postResult = httpsPost(url, paramMap);
			System.out.println("post请求返回结果是: "+postResult);
		} catch (Exception e) {
		// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("调用https失败:"+e);
		}
	}


	/**
	 * 批量发送相同内容短信:
	 * url https://118.178.116.15:8443/winnerrxd/api/SendBatchMsg
	 * userCode string 登录名称，必填
	 * userPass string 登录密码，必填
	 * DesNo string 手机号码，必填	 多个号码用英文逗号隔开 如: 13900000000,13900000001 每次提交不多于 50 个号码。
	 * Msg string 短信内容，必填。必须有短信签名 (Get 或者 Post 方式注意要用 UTF8 编码)
	 * autograph string 签名编号，非必填，留空
	 * smsType Integer 短信类型（101 触发类），非必填，可为空
	 * localhost:8080/msg2/sendMultiMessage
 	 */
	public void sendMultiMessage(){
		String url = "https://118.178.116.15:8443/winnerrxd/api/trigger/SendBatchMsg";
		/*Msg格式 签名必须有, 但是随你写, 没有签名就报错, 只不过没有头像, 能写中文 */
		String Msg="wsk1234【通联支付】"; //
		String DesNo="15932072636,18377153029,18377153092,17877143580";
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("userCode", userCode);
		paramMap.put("userPass", userPass);
		paramMap.put("DesNo", DesNo);
		paramMap.put("autograph", "");
		paramMap.put("Msg", Msg);
		paramMap.put("customerUuid", "");
		try {
			//GET请求
			final String getResult = ""; //httpsGet(url, paramMap);
			System.out.println(getResult);
			//POST请求
			String postResult = httpsPost(url, paramMap);
			System.out.println("post请求返回结果是: "+postResult);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("调用https失败:"+e);
		}
	}

	private static class TrustAnyTrustManager implements X509TrustManager {

		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}
		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}
		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}
	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}
	public static String httpsGet(String url,Map<String, String> params) throws
			Exception
	{
		String result = "";
		BufferedReader in = null;
		try {

			String urlStr = url + "?" + getParamStr(params);

			System.out.println("GET请求的URL为："+urlStr);
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
					new java.security.SecureRandom());
			URL realUrl = new URL(urlStr);
			// 打开和URL之间的连接
			HttpsURLConnection connection = (HttpsURLConnection)
					realUrl.openConnection();
			//设置https相关属性
			connection.setSSLSocketFactory(sc.getSocketFactory());
			connection.setHostnameVerifier(new TrustAnyHostnameVerifier());
			connection.setDoOutput(true);

			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();

			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new
					InputStreamReader(connection.getInputStream(),"UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			System.out.println("获取的结果为："+result);
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			//e.printStackTrace();
			throw e;
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				//e2.printStackTrace();
				throw e2;
			}
		}
		return result;

	}


	public static String httpsPost(String url, Map<String, String> params)
			throws Exception{
		String result = "";
		BufferedReader in = null;
		String content = getParamStr(params);
		try {
			System.out.println("POST请求的URL为："+url);
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
					new java.security.SecureRandom());
			//--------------------------------------------> 			URL console = new URL( url);
			// java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection cannot be cast to javax.net.ssl.HttpsURLConnection

			URL console = new URL( null , url, new sun.net.www.protocol.https.Handler());
			HttpsURLConnection connection = (HttpsURLConnection)
			console.openConnection();
			connection.setSSLSocketFactory(sc.getSocketFactory());
			connection.setHostnameVerifier(new TrustAnyHostnameVerifier());
			connection.setDoOutput(true);
			connection.connect();
			DataOutputStream out = new
					DataOutputStream(connection.getOutputStream());
			out.write(content.getBytes("UTF-8"));
			// 刷新、关闭
			out.flush();
			out.close();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new
					InputStreamReader(connection.getInputStream(),"UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			System.out.println("获取的结果为："+result);
		} catch (Exception e) {
			System.out.println("发送POST请求出现异常！" + e);
			//e.printStackTrace();
			throw e;
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				//e2.printStackTrace();
				throw e2;
			}
		}
		return result;
	}

	private static String getParamStr(Map<String, String> params)
	{
		String paramStr="";
		if(params != null && params.size() >0){
			// 获取参数列表组成参数字符串
			for (String key : params.keySet()) {
				paramStr+=key+"="+params.get(key)+"&";
			}
			//去除最后一个"&"
			paramStr=paramStr.substring(0, paramStr.length()-1);
		}
		return paramStr;
	}

}
